<?php
class Comments_mod extends CI_Model{

	function __construct(){
          parent::__construct();
	}

	/**
	 * 
	 * Dadavanje komentara u bazu
	 * @param array $data - podaci o komentaru (id_clanka i tekst komentara)
	 * 						id_comments, user_comment
	 */
	public function insertComment($data)
	{
		if($data['user_comment']!="") //Ako ima teksta u komentaru
		{
			$time = time();
			$sql = "INSERT INTO `comments` SET
					`datetime` = ".$time.",
					`text` = '".$data['user_comment']."' ,
					`article_id` = ".$data['id_article'].",
					`site_user_id` = ".$this->session->userdata('site_user_id').",
					`aproved` = 1
					;";
			$user_commnet = "<span class='commnet_time'>". date("d.m.Y H:i:s", $time)."</span> &nbsp;
							 <span class='site_user'>". $this->session->userdata('firstname') ." ". $this->session->userdata('lastname') ."</span> 
							 <br/><span class='commnet_text'>{$data['user_comment']}</span>";
			///*
			$this->db->query($sql);
			if($this->db->affected_rows())
				return 'true|Хвала за Ваш коментар.|'.$user_commnet;
			else
				return 'false|Дошло је до грешке приликом снимања коментара. Покушајте касније поново.';
			//*/
			//return "Id = {$data['id_article']}, Komentar: {$data['user_comment']}";
			 
			return 'true|Хвала за Ваш коментар.|'.$user_commnet;
		}
		else
			return 'false|Упишите прво коментар.';
	}
	
	public function getComments($article_id)
	{
		$sql = "SELECT `comments`.* , site_user.`firstname`, site_user.`lastname` FROM `comments`, `site_user`
				WHERE `article_id` = {$article_id}
					  AND comments.`site_user_id` =  site_user.`id`
					  AND `aproved` = 1
				ORDER BY datetime DESC
				;";
		$result = $this->db->query($sql);
		
		return $result->result_array();
		
	}
    
    public function getAllComments($aproved)
    {
        $query="
            SELECT comments.*, site_user.firstname, site_user.lastname, article.title
            FROM comments 
            LEFT JOIN article
            ON comments.article_id = article.id
            LEFT JOIN site_user
            ON comments.site_user_id = site_user.id
            WHERE comments.aproved = {$aproved}
            ORDER BY comments.datetime DESC
            
        ";
        
        $result = $this->db->query($query);
        
        return $result->result_array();
    }
      
}
		